<template>
  <div class="flex h-screen bg-gray-900 text-white">
    <!-- 使用统一的侧边栏组件，并应用深色主题 -->
    <Sidebar theme="dark" />

    <!-- Main content -->
    <div class="ml-72 flex-1 p-6 overflow-auto">
      <header class="flex justify-between items-center mb-6">
        <h2 class="text-3xl font-bold">智能数据处理平台数据大屏</h2>
        <div class="text-lg font-medium">{{ currentTime }}</div>
      </header>
      
      <div class="grid-stack"></div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, createApp, ref, onUnmounted } from 'vue';
import 'gridstack/dist/gridstack.min.css';
import { GridStack } from 'gridstack';
import ChartWidget from '../components/ChartWidget.vue';
import StatWidget from '../components/StatWidget.vue';
import type { EChartsOption } from 'echarts';
import Sidebar from '../components/Sidebar.vue';

type WidgetType = 'chart' | 'stat';

interface BaseWidgetData {
  id: string;
  x: number;
  y: number;
  w: number;
  h: number;
  type: WidgetType;
}

interface ChartWidgetData extends BaseWidgetData {
  type: 'chart';
  option: EChartsOption;
}

interface StatWidgetData extends BaseWidgetData {
  type: 'stat';
  value: string | number;
  label: string;
}

type WidgetData = ChartWidgetData | StatWidgetData;

// 当前时间
const currentTime = ref('');

// 更新时间函数
function updateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1 < 10 ? '0' : '') + (now.getMonth() + 1);
  const day = (now.getDate() < 10 ? '0' : '') + now.getDate();
  const hours = (now.getHours() < 10 ? '0' : '') + now.getHours();
  const minutes = (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
  const seconds = (now.getSeconds() < 10 ? '0' : '') + now.getSeconds();
  
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekday = weekdays[now.getDay()];
  
  currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${weekday}`;
}

let timeInterval: number | null = null;

/**
 * Generates mock data for the dashboard widgets.
 */
function getMockData(): WidgetData[] {
  const chartTextStyle = { color: '#e5e7eb', fontSize: 14 };
  const chartTitleStyle = { color: '#ffffff', fontSize: 18 };
  const axisLineStyle = { lineStyle: { color: '#4b5563' } };
  const splitLineStyle: { lineStyle: { color: string; type: 'dashed' | 'solid' | 'dotted' } } = { lineStyle: { color: '#374151', type: 'dashed' } };

  const pieChartOption: EChartsOption = {
    title: { text: "数据源类型", left: 'center', textStyle: chartTitleStyle },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left', textStyle: chartTextStyle },
    series: [ { name: '数据源', type: 'pie', radius: '60%', center: ['55%', '60%'], data: [ { value: 8, name: 'CSV 文件' }, { value: 5, name: 'PostgreSQL' }, { value: 2, name: 'API 接口' } ], emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ]
  };

  const barChartOption: EChartsOption = {
    title: { text: "热门智能体调用TOP5", left: 'center', textStyle: chartTitleStyle },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'value', boundaryGap: [0, 0.01], splitLine: splitLineStyle, axisLabel: { color: chartTextStyle.color } },
    yAxis: { type: 'category', data: ['报告Agent', '分析Agent', '代码Agent', '问答Agent', '邮件Agent'].reverse(), axisLabel: { color: chartTextStyle.color } },
    series: [ { name: '调用次数', type: 'bar', data: [182, 234, 290, 497, 630].reverse() } ]
  };

  const lineChartOption: EChartsOption = {
    title: { text: "最近消息量趋势", left: 'center', textStyle: chartTitleStyle },
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], axisLine: axisLineStyle, axisLabel: { color: chartTextStyle.color } },
    yAxis: { type: 'value', splitLine: splitLineStyle, axisLabel: { color: chartTextStyle.color } },
    series: [ { name: '消息量', type: 'line', stack: '总量', data: [120, 132, 101, 134, 90, 230, 210], areaStyle: {}, emphasis: { focus: 'series' } } ]
  };

    const stackedBarChartOption: EChartsOption = {
    title: { text: '消息分类统计', left: 'center', textStyle: chartTitleStyle },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { top: 'bottom', textStyle: chartTextStyle },
    grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
    xAxis: { type: 'value', splitLine: splitLineStyle, axisLabel: { color: chartTextStyle.color } },
    yAxis: { type: 'category', data: ['技术支持', '数据分析', '日常闲聊', '报告生成'], axisLabel: { color: chartTextStyle.color } },
    series: [
        { name: '用户消息', type: 'bar', stack: 'total', label: { show: true }, emphasis: { focus: 'series' }, data: [320, 302, 301, 334] },
        { name: 'AI 回复', type: 'bar', stack: 'total', label: { show: true }, emphasis: { focus: 'series' }, data: [220, 182, 191, 234] }
    ]
  };

  const radarChartOption: EChartsOption = {
    title: { text: '核心Agent能力评估', left: 'center', textStyle: chartTitleStyle },
    tooltip: { trigger: 'item' },
    legend: { data: ['分析Agent', '报告Agent'], bottom: 5, textStyle: chartTextStyle },
    radar: {
      indicator: [
        { name: '数据处理', max: 100 },
        { name: '逻辑推理', max: 100 },
        { name: '语言表达', max: 100 },
        { name: '稳定性', max: 100 },
        { name: '响应速度', max: 100 }
      ],
      axisName: {
          color: '#e5e7eb'
      }
    },
    series: [{
      name: 'Agent能力对比',
      type: 'radar',
      data: [
        { value: [95, 80, 85, 90, 75], name: '分析Agent' },
        { value: [70, 75, 95, 85, 90], name: '报告Agent' }
      ]
    }]
  };

  const gaugeChartOption: EChartsOption = {
      title: { text: '系统平均响应（ms）', left: 'center', textStyle: chartTitleStyle },
      series: [{
          type: 'gauge',
          center: ['50%', '60%'],
          axisLine: {
              lineStyle: {
                  width: 20,
                  color: [
                      [0.3, '#67e8f9'],
                      [0.7, '#38bdf8'],
                      [1, '#ef4444']
                  ]
              }
          },
          pointer: {
              itemStyle: {
                  color: 'auto'
              }
          },
          axisTick: {
              distance: -20,
              length: 8,
              lineStyle: {
                  color: '#fff',
                  width: 2
              }
          },
          splitLine: {
              distance: -20,
              length: 20,
              lineStyle: {
                  color: '#fff',
                  width: 4
              }
          },
          axisLabel: {
              color: 'inherit',
              distance: 30,
              fontSize: 14
          },
          detail: {
              valueAnimation: true,
              formatter: '{value} ms',
              color: 'inherit',
              fontSize: 20
          },
          data: [{
              value: 480
          }]
      }]
  };


  return [
    // Row 1
    { id: 'stat1', x: 0, y: 0, w: 2, h: 2, type: 'stat', value: 38, label: '智能体总数' },
    { id: 'stat2', x: 2, y: 0, w: 2, h: 2, type: 'stat', value: 15, label: '数据源' },
    { id: 'stat3', x: 4, y: 0, w: 2, h: 2, type: 'stat', value: 128, label: '生成报表数' },
    { id: 'stat4', x: 6, y: 0, w: 2, h: 2, type: 'stat', value: 76, label: '活跃用户' },
    { id: 'stat5', x: 8, y: 0, w: 2, h: 2, type: 'stat', value: '99.8%', label: '调用成功率' },
    { id: 'stat6', x: 10, y: 0, w: 2, h: 2, type: 'stat', value: '620ms', label: '平均响应' },
    // Row 2
    { id: 'barChart', x: 0, y: 2, w: 7, h: 4, type: 'chart', option: barChartOption },
    { id: 'pieChart', x: 7, y: 2, w: 5, h: 4, type: 'chart', option: pieChartOption },
    // Row 3
    { id: 'lineChart', x: 0, y: 6, w: 4, h: 4, type: 'chart', option: lineChartOption },
    { id: 'stackedBarChart', x: 4, y: 6, w: 4, h: 4, type: 'chart', option: stackedBarChartOption },
    { id: 'radarChart', x: 8, y: 6, w: 4, h: 4, type: 'chart', option: radarChartOption },
    // Row 4
    { id: 'gaugeChart', x: 0, y: 10, w: 4, h: 3, type: 'chart', option: gaugeChartOption },
  ];
}


onMounted(async () => {
  // 初始化时间并启动定时器
  updateTime();
  timeInterval = setInterval(updateTime, 1000);

  const grid = GridStack.init({
    column: 12,
    margin: 10,
    resizable: { handles: 'e, se, s, sw, w' }
  });

  const widgets: WidgetData[] = getMockData();

  widgets.forEach(widgetData => {
    const el = document.createElement('div');
    el.setAttribute('gs-x', String(widgetData.x));
    el.setAttribute('gs-y', String(widgetData.y));
    el.setAttribute('gs-w', String(widgetData.w));
    el.setAttribute('gs-h', String(widgetData.h));
    el.setAttribute('gs-id', widgetData.id);

    const content = document.createElement('div');
    content.className = 'grid-stack-item-content';
    el.appendChild(content);

    grid.addWidget(el);

    if (widgetData.type === 'chart') {
      const app = createApp(ChartWidget, { option: widgetData.option });
      app.mount(content);
    } else if (widgetData.type === 'stat') {
      const app = createApp(StatWidget, { value: widgetData.value, label: widgetData.label });
      app.mount(content);
    }
  });
});

onUnmounted(() => {
  // 清理定时器
  if (timeInterval) {
    clearInterval(timeInterval);
  }
});

</script>

<style>
/* To match the dark theme, we need to override some gridstack styles globally for this page */
.grid-stack {
  background: #111827; /* Darker background for the grid */
}
.grid-stack-item-content {
  color: #fff;
  background-color: #1f2937; /* Dark background for widgets */
  border-radius: 8px;
  border: 1px solid #374151;
  overflow: hidden;
}

.grid-stack-item.ui-resizable-resizing {
    z-index: 100;
}
</style> 